package com.dpwgc.demo.server;

import com.alibaba.fastjson.JSONObject;
import com.dpwgc.demo.mapper.GroupMapper;
import com.dpwgc.demo.model.Group;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 首页群组列表连接（监听用户群组列表，实时更新用户群组列表）
 */
@ServerEndpoint("/IndexLink/{userId}")
@Component
public class IndexLinkServer {

    private static GroupMapper groupMapper;

    //是否继续监听
    private volatile boolean flag;
    //当前用户ID
    private volatile String userId;

    //群组监听线程
    Thread thread = new Thread(){
        @Override
        public void run() {

            while (flag) {
                //获取用户加入的群组列表
                List<Group> groups = groupMapper.queryGroupByUserId(Integer.parseInt(userId));

                //转换为json字符串发送
                Object json = JSONObject.toJSON(groups);

                sendInfo(userId,json.toString());

                //每隔1秒访问一次数据库
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    //消息通道
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    //发送消息
    public static void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
                session.getBasicRemote().sendText(message);
            }
        }
    }
    //给指定用户发送信息
    public static void sendInfo(String userId, String message){
        Session session = sessionPools.get(userId);
        try {
            sendMessage(session, message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 建立连接成功调用
     * @param session 会话
     * @param userId 用户id
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId){
        sessionPools.put(userId, session);//添加用户
        addOnlineCount();

        this.userId=userId;
        this.flag=true;

        //开始群组监听进程
        thread.start();

        System.out.println(200);
    }

    /**
     * 关闭连接时调用
     * @param userId 用户id
     */
    @OnClose
    public void onClose(@PathParam(value = "userId") String userId){

        sessionPools.remove(userId);//删除用户
        subOnlineCount();

        //关闭进程
        flag=false;
        thread.interrupt();

        System.out.println(100);
    }

    @Autowired
    public void setRepository(GroupMapper groupMapper) {
        IndexLinkServer.groupMapper=groupMapper;
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(String message,@PathParam(value = "userId") String userId) throws IOException{


    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable){
        System.out.println("发生错误");
        throwable.printStackTrace();
    }

    public static void addOnlineCount(){
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }
}
